package correlationOfSalAndExp;

import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;

import java.io.IOException;

public class CorrelationMapper extends Mapper<Object, Text, Text, Text> {

    private Text outKey = new Text();
    private Text outValue = new Text();

    @Override
    protected void map(Object key, Text value, Context context) throws IOException, InterruptedException {

        String[] fields = value.toString().split(",");
        String X = fields[8];
        String Y = fields[6];

        double salary = getMaxSalary(Y);
        double experience = getExperienceInYears(X);

        //占位置
        outKey.set("Correlation");

        outValue.set(experience + "," + salary);

        context.write(outKey, outValue);
    }

    private double getMaxSalary(String salaryRange) {
        String[] salaryParts = salaryRange.split("-");
        if (salaryParts.length == 2) {
            try {
                // 提取最大值
                double upper = Double.parseDouble(salaryParts[1].replace("万", "").trim());
                return upper;
            } catch (NumberFormatException e) {
                return 0.0;
            }
        }
        return 0.0;
    }

    // 将经验年限转化为整数（按年数处理）
    private double getExperienceInYears(String experienceReq) {
        String extraS = "年";
        String conectS = "-";
        if (experienceReq.contains(extraS)) {
            //区间，"1-2年"
            if (experienceReq.contains(conectS)) {
                String[] parts = experienceReq.split(conectS);
                return Double.parseDouble(parts[1].replace(extraS, ""));
            } else {
                //单一年份，"x年"
                return Double.parseDouble(experienceReq.replace(extraS, ""));
            }
        }
        return 0.0;
    }
}
